package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.utils.ConstantUtil;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    VideoService videoService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    FastFileStorageClient client;

    @Autowired
    FdfsWebServer server;

    @DubboReference
    FocusUserService focusUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /*
    value:名称空间
    key:缓存中的key   用户id_页码_每页条数
    unless:当查询的页面中的数据为空的时候就不缓存
     */
    @Cacheable(value = "tanhua",key = "#userId+'_'+#pageNum+'_'+#pageSize",unless = "#result.counts==0")
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
        //1.远程调用videoService查询数据
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);

        //2.从pageBeanVo中获取视频列表
        List<Video> items = (List<Video>) pageBeanVo.getItems();

        //3.遍历视频列表,获取每个视频的发布人id,查询其userInfo,将视频和userInfo封装videoVo对象,将每个vo对方放入预先声明好的voList中
        List<VideoVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //获取发布者id,获取发布者userInfo
                Long videoUserId = video.getUserId();
                UserInfo userInfo = userInfoService.findByUserId(videoUserId);

                //3.将每个video和userInfo封装videoVo,将每个vo放入voList中
                VideoVo vo = new VideoVo();
                //先封装userInfo,再封装video
                vo.setUserInfo(userInfo);
                vo.setVideo(video);

                //判断用户是否关注过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId, videoUserId))) {
                    vo.setHasFocus(1);
                }

                voList.add(vo);
            }
        }
        //4.将voList设置给pageBeanVo
        pageBeanVo.setItems(voList);

        //5.返回pageBeanVo
        return pageBeanVo;
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    public void save(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.将封面和视频上传到FastDFS上,获取路径
        StorePath coverPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(),
                FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                FileUtil.extName(videoFile.getOriginalFilename()), null);

        //2.创建video对象,封装video
        Video video = new Video();

        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setPicUrl(server.getWebServerUrl()+coverPath.getFullPath());
        video.setVideoUrl(server.getWebServerUrl()+videoPath.getFullPath());

        System.out.println(video.getVideoUrl());
        System.out.println(video.getPicUrl());

        //3.远程调用service完成保存操作
        videoService.save(video);
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    public void focusUser(Long userId, Long focusUserId) {
        //1.封装focusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setCreated(System.currentTimeMillis());
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);

        //2.调用service完成保存操作
        focusUserService.save(focusUser);

        //3.往redis中保存关注的标识
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId),"1");
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    public void unFocusUser(Long userId, Long focusUserId) {
        //1.调用service完成删除操作
        focusUserService.delete(userId,focusUserId);

        //2.往redis中删除关注的标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId));
    }

}
